package com.example.tcpLearn.tcp5;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

/**
 * 多用户聊天室：客户端
 */
public class Client {
    public static void main(String[] args) throws IOException {

        System.out.println("客户端启动...");

        Socket socket = new Socket("127.0.0.1", 9999);

        OutputStream outputStream = socket.getOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

        InputStream inputStream = socket.getInputStream();
        DataInputStream dataInputStream = new DataInputStream(inputStream);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    while (true) {
                        String read = dataInputStream.readUTF();
                        System.out.println(read);
                        System.out.println("=========================");
                    }
                } catch (IOException e) {
                    System.out.println("退出聊天");
                }
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入需要发送的数据：");
            String msg = scanner.nextLine();
            if ("exit".equals(msg)) {
                System.out.println("客户端退出...");
                dataInputStream.close();
                dataOutputStream.close();
                socket.close();
                break;
            }
            dataOutputStream.writeUTF(msg);
            dataOutputStream.flush();
        }

    }
}
